//
//  TFTableViewCollectionItemCell.m
//  AppLibs
//
//  Created by 杜恺 on 2018/7/30.
//  Copyright © 2018年 jack Kong. All rights reserved.
//

#import "TFTableViewCollectionItemCell.h"
//Util
#import "TFTableViewCollectionItemManager.h"

@implementation TFTableViewCollectionItemCell

@dynamic tableViewItem;

#pragma mark - Cell life cycle

- (void)cellLoadSubViews {
    [super cellLoadSubViews];
    //add subviews and it's constraints at here.
    
}

- (void)cellWillAppear {
    [super cellWillAppear];
    //update subviews UI at here.
    [self addCollectionItemView];
}

- (void)addCollectionItemView {
    NSInteger section = [self.tableViewItem.manager.collectionItemsArray indexOfObject:self.tableViewItem];
    NSInteger itemCount = self.tableViewItem.layout.itemCount;
    for (UIView *subView in self.contentView.subviews) {
        if ([subView isKindOfClass:[TFTableViewCollectionItemView class]]) {
            [subView removeFromSuperview];
        }
    }
    for (NSInteger i = 0; i < itemCount; i++) {
        //移除之前的view
        UIView *itemView =
        self.tableViewItem.manager.itemViewForIndexPathBlock(self.tableViewItem.manager,self.tableViewItem,[NSIndexPath indexPathForRow:i inSection:section]);
        [self.contentView addSubview:itemView];
    }
}

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
    UIView *view = [super hitTest:point withEvent:event];
    if (event.allTouches.count) {
        [self hitContentViewAtPoint:point];
    }
    return view;
}

- (void)hitContentViewAtPoint:(CGPoint)point {
    NSInteger section = [self.tableViewItem.manager.collectionItemsArray indexOfObject:self.tableViewItem];
    NSInteger index = 0;
    
    for (UIView *subView in self.contentView.subviews) {
        if ([subView isKindOfClass:[TFTableViewCollectionItemView class]]) {
            if (CGRectContainsPoint(subView.frame, point)) {
                if (self.tableViewItem.manager.didSelectItemViewAtIndexBlock) {
                    self.tableViewItem.manager.didSelectItemViewAtIndexBlock(self.tableViewItem.manager,self.tableViewItem,(TFTableViewCollectionItemView *)subView,[NSIndexPath indexPathForRow:index inSection:section]);
                }
                break;
            }
            index++;
        }
    }
}

@end
